"""
weather.py -- Weather data plugin for CIB.
 Data provided by wunderground.com

 It's kinda weird cause you can only get the weather data via an airport code,
 or personal weather station. So you have to look them up first.
 If you give a zip code, or city, state pair, it'll give you a list of nearby
 airports and PWS's. I don't know what the best way to use which one is, but for
 now I just have it get data from the closest PWS.

 See: http://wiki.wunderground.com/index.php/API_-_XML
"""

import urllib2
from urllib import urlencode

try:
    from xml.etree.cElementTree import fromstring as etree_fromstring
except:
    from xml.etree.ElementTree import fromstring as etree_fromstring

irc = None

wu_loc = "http://api.wunderground.com/auto/wui/geo/GeoLookupXML/index.xml?%s"
wu_data_airport= "http://api.wunderground.com/auto/wui/geo/WXCurrentObXML/index.xml?query=%s"
wu_data_pws = "http://api.wunderground.com/weatherstation/WXCurrentObXML.asp?ID=%s"


def init(bot):
    global irc
    irc = bot

    irc.cmd.events['PRIVMSG'].subscribe(handle_privmsg)

def handle_privmsg(sender, args):
    msg = args[0].split()

    if msg[0] == '!wu':
        query = urlencode({'query': ' '.join(msg[1:])})

        try:
            req = urllib2.urlopen(wu_loc % query)
        except:
            print "!Error, could not access Weather Underground GeoLookup."
            req.close()
            return

        xml = req.read()
        tree = etree_fromstring(xml)
        req.close()

        if tree.tag == "wui_error":
            irc.notice(sender.nick, tree.find('title').text)
            return

        pws = tree.find('nearby_weather_stations/pws/station/id')
        station_id = pws.text
        try:
            req = urllib2.urlopen(wu_data_pws % station_id)
        except:
            print "!Error, could not access WU Weather Data"
            req.close()
            return

        tree = etree_fromstring(req.read())
        req.close()



        loc = tree.find('location/full').text
        temp = tree.find('temperature_string').text
        wind = tree.find('wind_string').text
        pressure = tree.find('pressure_string').text
        hi = tree.find('heat_index_string').text
        wc = tree.find('windchill_string').text

        irc.notice(sender.nick, "Current Conditions for %s" % loc)
        irc.notice(sender.nick, "Temperature: %s" % temp)

        if hi:
            irc.notice(sender.nick, "Heat Index: %s" % hi)
        elif wc:
            irc.notice(sender.nick, "Wind Chill: %s" % wc)

